package com.zh.kotlin_mvvm.ui

import android.app.Activity
import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.toast
import com.zh.kotlin_mvvm.databinding.ActivityRecordScreenBinding
import com.zh.kotlin_mvvm.service.RecordService

class RecordScreenActivity : BaseActivity<ActivityRecordScreenBinding>() {

    private var service: Intent? = null
    private var isRecording = true

    override fun initView(savedInstanceState: Bundle?) {

        val mediaManager =
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        viewBinding.apply {
            btnOpt.setOnClickListener {
                if (isRecording) {
                    btnOpt.text = "停止录制"
                    startActivityForResult(mediaManager.createScreenCaptureIntent(), 10001)
                } else {
                    btnOpt.text = "开始录制"
                    service = Intent(this@RecordScreenActivity, RecordService::class.java)
                    stopService(service)
                    isRecording = true
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 10001) {
            if (resultCode == Activity.RESULT_OK) {
                //获取权限，开启Service录制
                service = Intent(this@RecordScreenActivity, RecordService::class.java)
                service?.let {
                    it.putExtra("code", resultCode)
                    it.putExtra("data", data)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        startForegroundService(it)
                    } else {
                        startService(it)
                    }
                }
                isRecording = false
            } else {
                "取消".toast()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        service?.let { stopService(it) }
    }
}